<script setup lang="ts">
import dayjs from 'dayjs'
import { fetchProjectDetailAPI } from '@/apis/fetchProjectDetail'
import router from '@/router'
import { useProjectConfigStore } from '@/store/projectConfig'
import { useUserInfoStore } from '@/store/userInfo'
import { fetchProjectNodeListAPI } from '@/apis/fetchProjectNodeList'

const userInfoStore = useUserInfoStore()
const projectConfigStore = useProjectConfigStore()

const loading = ref(false)

const projectId = ref('')
const project = ref<Project | undefined>()

const activeNodes = ref<ProjectNode[]>([])
const allNodes = computed(() => {
  return projectConfigStore.nodeLists[project.value!.project_type_id!]
})

onLoad((options) => {
  if (options && options.project_id)
    projectId.value = options.project_id
})

onShow(async () => {
  if (projectId.value) {
    loading.value = true
    try {
      const res = await fetchProjectDetailAPI(
        projectId.value,
        userInfoStore.userInfo!.token!,
      )
      if (res.data?.code === 1) {
        project.value = res.data?.data
        const nodesRes = await fetchProjectNodeListAPI({
          project_id: projectId.value.toString(),
        }, userInfoStore.userInfo!.token!)
        if (res.data?.code === 1) {
          const ids = nodesRes.data?.data.map(item => item.node_id?.toString())
          const nodes = allNodes.value.filter(item => ids?.includes(item.id?.toString()))
          activeNodes.value = nodes
        }
        else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
      }
      else {
        uni.showToast({ title: res.data?.msg, icon: 'none' })
      }
    }
    catch (err) {
      uni.showToast({ title: JSON.stringify(err), icon: 'none' })
    }
    loading.value = false
  }
})

function getTableInfo(project?: Project) {
  return [
    ['装修面积', '装修风格', '户型'],
    [project?.extent || '未知', project?.zx_style || '未知', project?.house_type_name || '未知'],
    ['装修类型', '工期截止', '项目总额'],
    [project?.project_type_name || '未知', project?.duration ? dayjs.unix(Number(project.duration)).format('YYYY.MM.DD') : '未知', { value: project?.money_total ? `¥${project.money_total}` : '未知', highlight: true }],
    ['是否带家具', '是否带家电', ''],
    [project?.is_furniture ? '是' : '否', project?.is_appliance ? '是' : '否', ''],
  ]
}

function getListInfo(project?: Project) {
  return [
    { label: '位置', value: `${project?.province}${project?.city}${project?.district}` },
    { label: '详细地址', value: project?.address || '未知', isShowNavigationButton: true },
    { label: '业务员', value: project?.salesman?.nickname || '未知' },
  ]
}

/* ------------------------------- 通用事件处理 START ------------------------------- */
function handleCallContact() {
  if (project.value?.contacts_mobile) {
    uni.makePhoneCall({
      phoneNumber: project.value?.contacts_mobile,
      success: () => {},
      fail: () => { uni.showToast({ title: '呼叫取消', icon: 'none' }) },
    })
  }
}

function handleTapContactsCard() {
  router.push({
    name: 'projectContacts',
    params: {
      project_id: project.value!.id!.toString()!,
    },
  })
}

function handleTapProjectNodes() {
  router.push({
    name: 'projectNodes',
    params: {
      project_id: project.value!.id!.toString()!,
    },
  })
}

function handleNavigation() {
  if (project.value?.latitude && project.value.longitude) {
    uni.openLocation({
      name: project.value.address,
      latitude: Number(project.value.latitude),
      longitude: Number(project.value.longitude),
    })
  }
}

function handleInitiateAfterSales() {
  if (project.value?.id) {
    router.push({
      name: 'initiateAfterSales',
      params: {
        project_id: project.value.id.toString(),
      },
    })
  }
  else { uni.showToast({ title: '发生错误', icon: 'none' }) }
}

function handleAssignTeammates() {
  router.push({
    name: 'teammates',
    params: {
      project_id: project.value!.id!.toString(),
    },
  })
}

function handleViewPaymentRecord() {
  if (project.value?.id) {
    router.push({
      name: 'projectPaymentInfo',
      params: {
        project_id: project.value.id.toString(),
      },
    })
  }
  else {
    uni.showToast({ title: '发生错误', icon: 'none' })
  }
}
/* -------------------------------- 通用事件处理 END -------------------------------- */

/* ------------------------------ 业务员事件处理 START ----------------------------- */
function handleUpdateUserInfo() {
  if (project.value?.id?.toString()) {
    router.push({
      name: 'updateUserInfoInProject',
      params: {
        project_id: project.value?.id?.toString(),
        name: project.value.contacts_name || '',
        mobile: project.value.contacts_mobile || '',
      },
    })
  }
  else {
    uni.showToast({ title: '发生错误', icon: 'none' })
  }
}

function handleUploadPayment() {
  if (project.value?.id?.toString()) {
    router.push({
      name: 'uploadPayment',
      params: {
        project_id: project.value?.id?.toString(),
      },
    })
  }
  else {
    uni.showToast({ title: '发生错误', icon: 'none' })
  }
}
/* ------------------------------- 业务员事件处理 END ------------------------------ */

/* ------------------------------ 工长事件处理 START ------------------------------ */
function handleUpdateProjectNode() {
  router.push({
    name: 'updateProjectNode',
    params: {
      project_id: project.value!.id!.toString(),
    },
  })
}
/* ------------------------------- 工长事件处理 END ------------------------------- */

function handleSelectNode(nodeId?: number) {
  if (nodeId) {
    router.push({
      name: 'projectNodes',
      params: {
        project_id: project.value!.id!.toString(),
        node_id: nodeId.toString(),
      },
    })
  }
}
</script>

<template>
  <view class="page">
    <Spacer v-if="userInfoStore.belongTo(['1', '2', '3', '4'])" height="30" />
    <ContactCard
      v-if="userInfoStore.belongTo(['1', '2', '3', '4'])"
      :contact-name="project?.contacts_name ? project.contacts_name : '未知'"
      contact-identity="业主"
      :contact-mobile="project?.contacts_mobile ? project.contacts_mobile : '未知'"
      :show-edit-button="userInfoStore.belongTo(['4'])"
      @call="handleCallContact"
      @edit="handleUpdateUserInfo"
    />
    <Spacer height="30" />
    <view class="flex flex-col pt-30rpx px-30rpx pb-6rpx bg-white rounded-20rpx">
      <ProjectCardHeader
        :project-name="project?.name"
        :node-name="project?.node_name"
        :state="projectConfigStore.projectStatusStr[project?.status!]"
        :is-show-warning="false"
      />
      <Spacer height="20" />
      <Table :data="getTableInfo(project)" />
    </view>
    <Spacer height="30" />
    <view class="flex flex-col p-30rpx pb-20rpx bg-white rounded-20rpx">
      <view class="text-30rpx leading-30rpx text-secondary font-bold">
        已完成节点
      </view>
      <Spacer height="30" />
      <Divider />
      <Spacer height="30" />
      <ProjectNodes
        :active-nodes="activeNodes"
        :nodes="activeNodes"
        all-light-mode
        @select="handleSelectNode"
      />
    </view>
    <Spacer height="30" />
    <ProjectInfoCard
      :info-list="getListInfo(project)"
      picture-label="合同照片"
      :pictures="project?.contract_images?.split(',') ? project?.contract_images?.split(',') : []"
      :desc="project?.ask || '未知'"
      @navigate="handleNavigation"
    />
    <Spacer height="30" />
    <view class="flex flex-col p-30rpx bg-white rounded-20rpx">
      <view class="text-30rpx leading-30rpx text-secondary font-bold">
        项目功能
      </view>
      <Spacer height="30" />
      <Divider />
      <Spacer height="36" />
      <ProjectCardActions @tap-contacts="handleTapContactsCard" @tap-project-nodes="handleTapProjectNodes" />
    </view>
    <Spacer height="270" />
    <view v-if="userInfoStore.belongTo(['4']) && projectConfigStore.projectStatusStr[project?.status!] === '施工中'" class="fixed bottom-80rpx x-center flex justify-between items-center w-690rpx">
      <RGButton width="280" type="secondary" size="large" @tap="handleUpdateProjectNode">
        修改节点
      </RGButton>
      <RGButton width="392" type="primary" size="large" @tap="handleUploadPayment">
        上传打款凭证
      </RGButton>
    </view>
    <view v-if="userInfoStore.belongTo(['2']) && projectConfigStore.projectStatusStr[project?.status!] === '施工中'" class="fixed bottom-80rpx x-center flex justify-between items-center w-690rpx">
      <RGButton width="280" type="secondary" size="large" @tap="handleAssignTeammates">
        设置团队人员
      </RGButton>
      <RGButton width="392" type="primary" size="large" @tap="handleUpdateProjectNode">
        修改项目节点
      </RGButton>
    </view>
    <RGButton
      v-if="userInfoStore.belongTo(['0', '4', '2']) && projectConfigStore.projectStatusStr[project?.status!] === '售后中'"
      class="fixed bottom-80rpx x-center"
      type="primary"
      size="large"
      @tap="handleInitiateAfterSales"
    >
      发起售后
    </RGButton>
    <RGButton
      v-if="userInfoStore.belongTo(['1'])"
      class="fixed bottom-80rpx x-center"
      type="primary"
      size="large"
      @tap="handleAssignTeammates"
    >
      设置团队人员
    </RGButton>
    <RGButton
      v-if="userInfoStore.belongTo(['3'])"
      class="fixed bottom-80rpx x-center"
      type="primary"
      size="large"
      @tap="handleViewPaymentRecord"
    >
      查看打款信息
    </RGButton>
    <RGButton
      v-if="userInfoStore.userInfo!.group_id! >= 5"
      class="fixed bottom-80rpx x-center"
      type="primary"
      size="large"
      @tap="handleUpdateProjectNode"
    >
      修改项目节点
    </RGButton>
    <image
      v-if="userInfoStore.belongTo(['4'])"
      class="z-10 fixed right-0 bottom-200rpx w-122rpx h-125rpx"
      src="@/static/images/pay_record.png"
      @tap="handleViewPaymentRecord"
    />
  </view>
  <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'projectDetail'
style:
  navigationBarTitleText: '项目详情页'
</route>
